package com.lzp.customview.togglebtn

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.customview.widget.ViewDragHelper
import com.utils.SizeUtils
import com.view.ViewHelper
import kotlin.math.roundToInt

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 3/3/21
 */
class SeekBarWithText : FrameLayout {

    private val TAG = "SeekBarWithText"
    private val dp1 = SizeUtils.dip2px(context, 1)

    private var viewWidth = 0
    private var viewHeight = 0

    private val textView = TextView(context)
    private val textSize = 15f
    private val textColor = 0xff2c2d2e.toInt()
    private val textWidth = 500

    //进度条部分
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
    private var progressColor = Color.parseColor("#ffcfd7e2")
    private var progressSelectedColor = Color.parseColor("#ff2c2d2e")
    private val progressLineHeight = dp1 * 2

    private val lineTopMargin = dp1*49
    private val toggleTopMargin = dp1*36

    //进度条的宽度
    private var progressWidth = 0f

    private var toggleView = View(context)
    private var toggleViewSize = dp1 * 28


    private val dragHelper: ViewDragHelper = ViewDragHelper.create(this, DragHelperCallBack())

    private var progress = 0f


    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    init {
        progressPaint.color = progressColor
        progressPaint.style = Paint.Style.STROKE
        progressPaint.strokeWidth = progressLineHeight.toFloat()
        progressPaint.strokeCap = Paint.Cap.ROUND
        val layoutParams = LayoutParams(toggleViewSize,toggleViewSize)
        layoutParams.topMargin = toggleTopMargin
        toggleView.layoutParams = layoutParams
        toggleView.background = ViewHelper.createShapeDrawable(toggleViewSize/2f,0xffffffff.toInt())
        toggleView.elevation = dp1*3f
        addView(toggleView)

        textView.textSize = textSize
        textView.setTextColor(textColor)
        textView.gravity = Gravity.CENTER
        textView.paint.isFakeBoldText = true
        val textLayout = LayoutParams(textWidth,(dp1*22.5).toInt())
        textView.layoutParams = textLayout
        addView(textView)
    }

    inner class DragHelperCallBack : ViewDragHelper.Callback() {
        override fun tryCaptureView(child: View, pointerId: Int): Boolean {
            return child == toggleView
        }

        override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
            var tempLeft = left
            if (left < 0) {
                tempLeft = 0
            } else if (left > width - toggleViewSize) {
                tempLeft = width - toggleViewSize
            }
            progress = tempLeft / progressWidth
            updateText(progress)
            postInvalidate()
            return tempLeft
        }

        override fun clampViewPositionVertical(child: View, top: Int, dy: Int): Int {
            return toggleTopMargin
        }

        override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
            //停止滚动之后
        }
    }

    private fun updateText(progress: Float) {
        textView.text = interpolator.progress2showText(progress)
        textView.post {
            textView.translationX = progress*progressWidth+toggleViewSize/2  - textWidth/2
        }
    }

    override fun computeScroll() {
        //回弹时刷新界面
        if (dragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this)
        }
    }

    override fun dispatchDraw(canvas: Canvas?) {
        drawLine(canvas)
        super.dispatchDraw(canvas)

    }

    private fun drawLine(canvas: Canvas?) {
        if (canvas == null) {
            return
        }
        val startX = toggleViewSize / 2f
        val endX = progress*progressWidth+toggleViewSize/2
        //画背景
        progressPaint.color = progressColor
        canvas.drawLine(startX, lineTopMargin.toFloat(), viewWidth - toggleViewSize / 2f, lineTopMargin.toFloat(), progressPaint)
        //画0-进度的线
        progressPaint.color = progressSelectedColor
        canvas.drawLine(startX,lineTopMargin.toFloat(),endX,lineTopMargin.toFloat(), progressPaint)

    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (w != 0 && h != 0) {
            viewWidth = w
            viewHeight = h
            progressWidth = viewWidth - toggleViewSize.toFloat()
            updateText(progress)
        }
    }

    fun setProgress(progress: Float) {
        this.progress = progress
        post {
            dragHelper.smoothSlideViewTo(toggleView, (progressWidth * progress / 100f).toInt(), 0)
            ViewCompat.postInvalidateOnAnimation(this)
        }
    }

    fun getProgress(): Float {
        return progress
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (ev != null) {
            dragHelper.shouldInterceptTouchEvent(ev)
        } else {
            super.onInterceptTouchEvent(ev)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            dragHelper.processTouchEvent(event)
            return true
        }
        return super.onTouchEvent(event)
    }

    private var progressChangedListener: OnProgressChangedListener? = null
    fun setOnProgressChangedListener(progressChangedListener: OnProgressChangedListener?) {
        this.progressChangedListener = progressChangedListener
    }

    interface OnProgressChangedListener {
        fun onProgressChange(progress: Float)
    }


    private var interpolator: Interpolator = DefaultInterpolator()
    fun setInterpolator(interpolator: Interpolator) {
        this.interpolator = interpolator
    }


    //*********以下为插值器，可根据需要动态修改文字显示**********
    /**
     * 默认插值器，显示百分比
     */
    class DefaultInterpolator : Interpolator {
        override fun progress2showText(progress: Float): String {
            return (progress * 100).roundToInt().toString()/*"${(4+progress*21f).roundToInt()}km/h"*/
        }
    }

    interface Interpolator {
        /**
         * 根据当前的progress，按显示规则显示文字
         */
        fun progress2showText(progress: Float): String
    }
}